package mqlistener

import (
	log "ac-common-go/glog"
	"ac-julink/manager"
	"ac-julink/socket"
	"ac-julink/tool/data"
	hsjson "ac-julink/tool/json"
	"ac-julink/tool/procinfo"
	"ac-julink/tool/util"
	"errors"
	"strings"
	"time"
	//"github.com/jjeffery/stomp"
	"ac-julink/cache"
	"github.com/go-stomp/stomp"
)

func NewWgmcuListener() *WgmcuActiveMqListener {
	return &WgmcuActiveMqListener{}
}

type WgmcuActiveMqListener struct {
}

func (self *WgmcuActiveMqListener) OnReceive(msg *stomp.Message, context *cache.SyncContext, client *manager.AcRestClient) (err error) {
	timeStart := time.Now().UnixNano()
	defer func() {
		if pErr := recover(); pErr != nil {
			log.Errorf("WgmcuActiveMqListener OnReceive panic:%+v\n%s", pErr, util.PanicTrace())
		}
	}()
	if msg == nil || msg.Body == nil {
		return errors.New("stomp.Message invalid")
	}
	log.Infof("Wgmcu MQ OnReceive:%s", string(msg.Body))
	_fdid, _wifiid, _result, _msgid, err := DealWgmcuMq(string(msg.Body), context, client)
	if err != nil {
		if !strings.Contains(err.Error(), "on other sid") {
			log.Errorf("DealWgmcuMq failed !%+v", err)
		}
		return err
	}
	log.Infof("DealWgmcuMq fd[%d],wifiid[%s],result:%s", _fdid, _wifiid, _result)

	socketSession := socket.SocketManager.SessionMgr.GetSession(_fdid)
	if socketSession != nil {
		log.Infof("socketSession:[%s]", socketSession.WifiID())
		if strings.Compare(socketSession.WifiID(), _wifiid) != 0 {
			log.Errorf("Not Find Session!")
			return errors.New("Not Find Session!")
		}

		socketSession.SendMessage(_result)
	} else {
		log.Errorf("Get [%d] socketSession failed !", _fdid)
		return errors.New("socketSession is nil!")
	}
	log.Warningf("RECORD-WgmcuMQ:%d,%s,%dms,err:%+v", _msgid, _wifiid, (time.Now().UnixNano()-timeStart)/1e6, err)
	return nil
}

// 处理WGMCU升级指令MQ消息
func DealWgmcuMq(_jsonstr string, context *cache.SyncContext, client *manager.AcRestClient) (fdid int, wifid, reponse string, msgid int, err error) {
	var isHENC bool
	procinfo.AddCount(data.SEND_MCU_UPGRADE_COMMAND)
	//1.解析MQ数据
	_wifiid, _type, _ver, _md5, _checksum, _addr, _filesize, _effectiveStart, _effectiveLen, err := hsjson.MQParseMsgMcu(_jsonstr)
	if err != nil {
		log.Errorf("MQParseMsgMcu  failed! ", err)
		return fdid, _wifiid, reponse, 305, err
	}
	//2.查询PS设备在线状态
	var online int
	var sid string
	//var ip string
	resp, err := client.GetWifiStats(_wifiid)
	if err != nil {
		log.Errorf("GetWifiStats  failed! ", err)
		return fdid, _wifiid, reponse, 305, err
	} else {
		if value, ok := resp["stat"]; ok && value != nil {
			online = int(value.(float64))
		}
		if value, ok := resp["owner"]; ok && value != nil {
			sid = value.(string)
		}
		if value, ok := resp["netid"]; ok && value != nil {
			fdid = int(value.(float64))
		}

		if value, ok := resp["cbcEnable"]; ok && value != nil {
			isHENC = value.(bool)
		}
	}
	if len(sid) == 0 {
		log.Errorf("sid in cannot be empty for [%v]!", resp)
		return fdid, _wifiid, "", msgid, errors.New("invalid wifiStats, sid is nil!")
	}

	log.Infof("GetWifiStats online:%d,sid:%s,fdid:%d", online, sid, fdid)
	//3.判断设备是否在线,sid是否为此节点
	if online != 1 {
		log.Errorf("wifiid[%s] offline!", _wifiid)
		return fdid, _wifiid, "", 305, errors.New("Device is offline!")
	}

	if strings.Compare(data.Mysid, sid) != 0 {
		log.Infof("Device on other sid[%s]!", sid)
		return fdid, _wifiid, "", 305, errors.New("Device on other sid!")
	}

	//4.组装下发JSON数据
	_json, err := hsjson.McuJsonCreate(_type, _ver, _md5, _addr, _checksum, _filesize, _effectiveStart, _effectiveLen)
	if err != nil {
		log.Errorf("McuJsonCreate failed !", err)
		return fdid, _wifiid, "", 305, err
	}
	//6.根据wifiid,获取预制密钥
	pre_key, _ := client.GetPublicKey(_wifiid, isHENC, context)
	log.Infof("pre_jey[%s]", pre_key)
	//7.pacakage msg,组装HS{}MD5\r\n格式数据包
	_msgResult := data.PackageMsg(_json, pre_key)
	log.Infof("DealWgmcuCmdMq:[%s]", _msgResult)
	return fdid, _wifiid, _msgResult, 305, err
}
